#!/usr/bin/ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require 'sinatra'

require_relative '../../src/lib/web_backend.rb'
require_relative '../../src/lib/service_logs/service_logs.rb'

set :bind, '0.0.0.0'
set :port, 10002
set :show_exceptions, false
set :environment, :production

# GET /web_backend/compare_candidates
# Response:
# - {"query_conditions": {...}, "dimension": [...]}
get '/web_backend/compare_candidates' do
  compare_candidates
end

# GET /web_backend/compare?suite=borrow&dimension=tbox_group
# must:
# - query_conditions
#   - os / os_version / suite / os_arch / tbox_group
# - dimension
#   - os / os_version / os_arch / suite / tbox_group
#
# Response:
#   - compare result string / "No Data." / "No Difference."
get '/web_backend/compare' do
  compare(params)
end

# GET /web_backend/get_jobs?upstream_repo=a&page_size=12&start_date=2020-11-03&end_date=2020-11-03
# optional:
# - upstream_repo
#   - regex search
# - os
# - os_version
# - os_arch
# - suite
# - category
# - testbox
# - job_state
# - id
# - start_date
# - end_date
# - page_size
#   - default: 20
# - page_num
#   - default: 1
#
# Response:
#   - default: 20 jobs
get '/web_backend/get_jobs' do
  get_jobs(params)
end

# GET /web_backend/active_testbox
# return to testbox that are active within 30 minutes
get '/web_backend/active_testbox' do
  get_active_testbox
end

# GET /web_backend/srpm_info?page_size=1&page_num=2&softwareName=vim-enhanced
# - page_size
# - page_from

get '/web_backend/srpm_info' do
  get_srpm_info(params)
end

# GET /web_backend/compat_software_info?page_size=1&page_num=2&os="openeuler 20.03 LTS"&arch=aarch64&keyword=vim-enhanced
# - page_size
# - page_num
# - os
# - arch
# - type
# - keyword
get '/web_backend/compat_software_info' do
  get_compat_software(params)
end

# GET /web_backend/query_compat_software
get '/web_backend/query_compat_software' do
  get_compat_software_info_detail
end

# GET /web_backend/get_repos?git_repo=a&page_size=12&page_num=3
# optional:
# - git_repo
# - page_size
#   - default: 20
# - page_num
#   - default: 1
#
# Response:
#   - default: 20 repos
get '/web_backend/get_repos' do
  get_repos(params)
end

# POST /web_backend/performance_result
# - header: "Content-Type: Application/json"
# - body: json
#   eg:
#     {
#       "metrics": ["fio.write_iops", "fio.read_iops"],
#       "filter":{
#           "suite": ["fio-basic"],
#           "os_arch": ["aarch64", "x86"]
#         },
#       "series": [
#           {
#             "os": "debian",
#             "os_version": "sid"
#           },
#           {
#             "os": "openeuler",
#             "os_version: 20.03
#           }
#         ],
#       "x_params": ["bs", "test_size"],
#     }
#
# Response:
#   - performance result
post '/web_backend/performance_result' do
  request.body.rewind # in case someone already read it
  performance_result(request.body.read)
end

# POST /web_backend/query_field
# - header: "Content-Type: Application/json"
# - body: json
#   eg:
#   {
#     "filter": {"suite": ["stream"]},
#     "field": "os"
#   }
#   return:
#   eg: ["openeuler", "centos", "debian", "openanolis", "kylin", "uniontechos"]
post '/web_backend/query_field' do
  request.body.rewind
  query_filed(request.body.read)
end

# GET /web_backend/get_testboxes
# Response:
#   - { total: total, testboxes[ 'testbox1', 'testbox2', ... ] }
get '/web_backend/get_testboxes' do
  query_testboxes
end

# GET /web_backend/get_tbox_state?testbox=$testbox
# Response:
#   - {
#       testbox: $testbox,
#       states: {
#         "state": "$current_state",
#         "job_id": "$current_job_id",
#         "history": [
#           {
#             "time": "$history_time",
#             "mac": "$mac",
#             "ip": "$ip",
#             "job_id": "$history_job_id",
#             "state": "$history_state"
#           },
#           ...
#         ]
#       }
#     }
get '/web_backend/get_tbox_state' do
  get_tbox_state(params)
end

# GET /web_backend/get_repo_statistics?git_repo=$git_repo
# Response:
#   - {
#       "title": "new refs statistics",
#       "unit": "times",
#       "x_name": "date",
#       "source": [["x_params", $date1, ..., $date_today],
#                  ["new_ref_times", $times_1, ..., $times_today]]
#     }
get '/web_backend/get_repo_statistics' do
  new_refs_statistics(params)
end

# GET /web_backend/get_jobs_summary?suite=iperf&GROUP_BY=my_name
# must:
# - query_conditions
#   - suite / group_id / ...
# - GROUP_BY
#   - group_id / my_email / my_name
#
# Response like:
#   - {
#       "filter": {
#         "suite": "$suite",
#         "GROUP_BY": "$GROUP_BY"
#        },
#       "attributes": ["$group_by", 'nr_all', 'nr_pass', 'nr_fail'],
#       "objects": [
#         {
#           "$group_by": "kezhiming"
#           "nr_all": $nr_all,
#           "nr_pass": $nr_pass,
#           "nr_fail: $nr_fail
#         },
#         ...
#       ]
#     }
get '/web_backend/get_jobs_summary' do
  group_jobs_stats(params)
end

# GET /web_backend/get_job_error?suite=virttest&tbox_group=vm-2p8g&group_id=wcl_ansible-openeuler-03-10
# Response
# {
#   "filter": {
#     "suite": "virttest",
#     "tbox_group": "vm-2p8g",
#     "group_id": "wcl_ansible-openeuler-03-10"
#   },
#   "attributes": ["job_id", "error_message", "result_root", "stderr"],
#   "objects": [
#      {
#        "job_id": "crystal.1354921",
#        "error_message": "{\"changed\": false, \"msg\": \"Unable to start service httpd: Job for httpd.service failed because a timeout was exceeded.}",
#        "result_root": "/result/ansible_test/2021-03-10/vm-2p16g--wcl1/openeuler-20.03-aarch64/yogeshraheja-ansible-httpdtemplate/crystal.1354921",
#        "stderr": "/result/ansible_test/2021-03-10/vm-2p16g--wcl1/openeuler-20.03-aarch64/yogeshraheja-ansible-httpdtemplate/crystal.1354921/stderr"
#      },
#      ...
#   ]
# }
get '/web_backend/get_job_error' do
  get_job_error(params)
end

# GET /web_backend/git_mirror_health
# Response:
# - [ "state", "alive_num", "msg_count" ]
get '/web_backend/git_mirror_health' do
  git_mirror_health
end

# POST /web_backend/active_service_error_log
# - header: "Content-Type: Application/json"
# - body: json
#
# Response:
#   - show all services error/warn messages
#   eg:
#     { "total": 4,
#       "cols": ["first_date","service","count","error_message"],
#       "filter": {"start_time":"2021-06-21 14:17:32","end_time":"2021-06-22 14:17:32"},
#       "data": [
#                  {"first_date":"2021-06-18 06:11:04","service":"scheduler-3000", "count":"503", "error_message":"Failed to verify the account."},
#                  {"first_date":"2021-06-18 06:09:38","service":"scheduler-3000", "count":"110", "error_message":"Error reading socket: Connection reset by peer"},
#                  {"first_date":"2021-06-18 06:09:46","service":"scheduler-3000", "count":"10", "error_message":"Queues are not registered for this testbox: "},
#                  {"first_date":"2021-06-18 01:24:54","service":"scheduler-3000", "count":"3", "error_message":"Missing hash key: \"pkgbuild_repo\""}
#              ]
#     }
post '/web_backend/active_service_error_log' do
  active_service_error_log
end

# POST /web_backend/active_stderr
# - header: "Content-Type: Application/json"
# - body: json # just a empty {}
# - output:
# {
#   "total":74,
#   "cols":["count","first_date", "suite", "job_owner", "relevant_links","error_message"],
#   "data":[
#     {
#       "count":43,
#       "first_date":"2021-06-22",
#       "job_owner": "compass-ci-robot",
#       "suite": "iperf",
#       "relevant_links":"/result/host-info/2021-07-05/vm-2p8g/openeuler-20.03-aarch64/crystal.2654417",
#       "error_message":"stderr.Can_not_find_perf_command"
#     },
#     ...
#   ]
# }
post '/web_backend/active_stderr' do
  active_stderr
end

# POST /web_backend/job_boot_time
# - header: "Content-Type: Application/json"
# - body: json
#
# Response:
#   - show job id which job state is boot and boot time at now
#   eg:
#     {
#       "vm": {
#         "threshold": 180(second),
#         "x_params": [job_id, job_id2, job_id3, ...]
#         "boot_time": [100, 0, 110, ...]
#       }
#     }
#       "dc": {
#         "threshold": 60(second),
#         "x_params": [job_id, job_id2, job_id3, ...]
#         "boot_time": [100, 0, 110, ...]
#       }
#     }
#       "hw": {
#         "threshold": 600(second),
#         "x_params": [job_id, job_id2, job_id3, ...]
#         "boot_time": [100, 0, 110, ...]
#       }
#     }
post '/web_backend/job_boot_time' do
  job_boot_time
end

# POST /web_backend/top_boot_time
# - header: "Content-Type: Application/json"
# - body: json # just a empty {}
# - output:
# {
#   "hw": [
#     {
#       "job_id1": $job_id1,
#       "boot_time": $boot_time,
#       "result_root": $result_root
#     },
#     ...
#   ],
#   "vm": [
#     {
#       "job_id2": $job_id2,
#       "boot_time": $boot_time,
#       "result_root": $result_root
#     },
#     ...
#   ],
#   "dc": [
#     {
#       "job_id3": $job_id3,
#       "boot_time": $boot_time,
#       "result_root": $result_root
#     },
#     ...
#   ]
# }
post '/web_backend/top_boot_time' do
  top_boot_time
end

get '/web_backend/test_matrix' do
  query_test_matrix(params)
end

# GET /web_backend/host_info?testbox=taishan200-2280-2s48p-256g--a1008
# Response:
#   - host_info(JSON)
get '/web_backend/host_info' do
  query_host_info(params)
end
